package com.usian.controller;

import com.usian.OrderFeign;
import com.usian.feign.CarFeign;
import com.usian.pojo.*;
import com.usian.utils.JsonUtils;
import com.usian.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/frontend/order")
@RestController
public class OrderWebController {

    @Autowired
    OrderFeign orderFeign;

    @Autowired
    CarFeign carFeign;

    /**
     *  创建订单
     *
     * @param orderItem
     * @param tbOrder
     * @param tbOrderShipping
     * @return
     */
    @RequestMapping("insertOrder")
    public Result insertOrder(String orderItem, TbOrder tbOrder , TbOrderShipping
            tbOrderShipping) {
        //因为一个request中只包含一个request body. 所以feign不支持多个@RequestBody。
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderItem(orderItem);
        orderInfo.setTbOrder(tbOrder);
        orderInfo.setTbOrderShipping(tbOrderShipping);
        Long orderId = orderFeign.insertOrder(orderInfo);
        if (orderId != null) {
            //删除购物车
            return Result.ok(orderId);
        }
        return Result.error("error");
    }

    /**
     * 订单确认
     *
     * @param ids
     * @param userId
     * @return
     */
    @RequestMapping("goSettlement")
    public Result goSettlement(String[] ids,String userId){
        //获取购物车中的信息
        Map<String, TbItem> cart = carFeign.selectCartByUserId(userId);
        //从购物车获取选中的商品
        List<TbItem> list = new ArrayList<>();
        for (String id : ids) {
            list.add(cart.get(id));
        }
        //购物车有商品返回list
        if (list != null && list.size() > 0){
            return Result.ok(list);
        }
        //购物车没有商品返回error
        return Result.error("error");
    }

}
